<template>
	<div class="system-role">
        
		<div class="top">
			<Row :gutter="10" justify="center">
				<Col span="4">
					<Button type="success" icon="md-add" @click="showDrawer=true;">新增</Button>
				</Col>
			</Row>
		</div>
		<Drawer :title="alertTitle" v-model="showDrawer" :width="720" :mask-closable="false">
			<Form :model="editedItem" >
				<Row :gutter="32">
					<Col span="12">
						<FormItem label="用户名称" label-position="top">
							<Input v-model="editedItem.username" maxlength="30" placeholder="请输入用户名称" />
						</FormItem>
					</Col>

					<Col span="12">
						<FormItem label="性别" label-position="l">
							<RadioGroup class="label-group" v-model.number="editedItem.sex">
								<Radio v-for="(item,i) in GLOBAL.sexOptionList" :key="i" :label="item.value">{{item.text}}</Radio>
							</RadioGroup>
						</FormItem>
					</Col>
				</Row>
				<Row :gutter="32">
					<Col span="12" v-if="editedIndex===-1">
						<FormItem label="手机号" label-position="top">
							<Input v-model="editedItem.mobile" maxlength="11" placeholder="手机号" />
						</FormItem>
					</Col>
					<Col span="12" v-if="editedIndex===-1">
						<FormItem label="密码" label-position="top">
							<Input v-model="editedItem.password" maxlength="30" placeholder="请设置登录密码" />
						</FormItem>
					</Col>
				</Row>
				<Row :gutter="32">
					<Col span="12">
						<FormItem label="角色" label-position="top">
							<Select v-model="editedItem.roleIds" multiple :max-tag-count="10" placeholder="请选择角色">
								<Option v-for="item in roleIds" :value="item.id" :key="item.id">{{ item.rolename}}</Option>
							</Select>
						</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" @click="save" :loading="editedIndex===-1?createLoading:updateLoading">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
				>
					<template slot-scope="{ row }" slot="sex">
                        <span v-if="Number(row.sex)===1">男</span>
                        <span v-else-if="Number(row.sex)===2">女</span>
                        <span v-else>-</span>
                    </template>
					<template slot-scope="{row}" slot="createTime">
						<span>{{row.createTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="updateTime">
						<span>{{row.updateTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="action">
						<Button type="primary" size="small" @click="update(row)">修改</Button>
						<Button type="primary" size="small" @click="userUpdatePassword(row)">修改密码</Button>
						<Button class="ml10" type="primary" ghost size="small" @click="remove(row)">删除</Button>
					</template>
				</Table>
				
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>
import { userGet, userUpdate, userDelete, userAdd, userPageQueryList, userUpdatePassword, userUpdateUserPassword } from '../../../api/user.js'
import { rolePageQueryList } from '../../../api/role.js'
export default {
	data() {
		return {
			showDrawer: false,
			loading: false,
			updateLoading: false,
            createLoading: false,
            updatePasswordLoading: false,
			editedIndex: -1,
			editedItem: {
				sex: '',
				username: '',
				roleIds: [],
				mobile: '',
				password: ''
			},
			defaultItem: {
				sex: '',
				username: '',
				roleIds: [],
				mobile: '',
				password: ''
			},
			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			roleIds: [],
			tableColumns: [
				// {
				// 	title: '用户id',
				// 	key: 'id'
				// },
				// {
				// 	title: '头像',
				// 	width: 130,
				// 	key: 'headimgurl'
				// },
				{
					title: '用户名',
					width: 130,
					key: 'username'
				},
				{
					title: '手机号',
					width: 130,
					key: 'mobile'
				},
				{
					title: '性别',
					slot: 'sex'
				},
				{
					title: '创建者id',
					key: 'createUserId',
					width: 130
				},
				
				{
					title: '用户类型',
					key: 'userType'
				},
				{
					title: '状态',
					key: 'status'
				},
				{
					title: '创建时间',
					slot: 'createTime'
				},
				{
					title: '更新时间',
					slot: 'updateTime'
				},
				{
					title: '操作',
					slot: 'action',
					width: 250
				}
            ],
            oldPassword: '',
            password: '',
		}
	},
	mounted() {
		this.userPageQueryList()
        this.rolePageQueryList() //角色列表
	},
	computed: {
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
		}
	},
	methods: {
		userUpdatePassword(row) {
            const{ id,username } = row;
            
			this.$Modal.confirm({
                title:`修改 ${username} 的密码`,
				render: h => {
					return h('div', [
						h('Input', {
							props: {
                                value: this.oldPassword,
								autofocus: true,
                                placeholder: '请输入旧密码',
							},
							on: {input: val => this.oldPassword = val,}
                        }),
                        h('Input', {
							props: {
                                value: this.password,
                                placeholder: '请输入新密码',
                            },
                            class:['mt10'],
							on: {input: val => this.password = val}
						}),
					])
                },
                onOk: async () => {
                    const { password, oldPassword} = this;
                    this.updatePasswordLoading || (this.updatePasswordLoading = true)
                    const res = await userUpdatePassword({id,password,oldPassword})
                    this.updatePasswordLoading = false;
                    this.modal(res,'修改密码');
                    this.rolePageQueryList();
                    if (res.code === '0') {
                        this.password = '';
                        this.oldPassword = '';
                    }
                }
			})
		},
		rolePageQueryList() {
			rolePageQueryList({
				page: 1,
				pageSize: 100
			}).then(res => {
				console.log('rolePageQueryList-->', res)
				res.code === '0'
					? (this.roleIds = res.data.items)
					: this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
					  })
			})
		},
		pageChange(page) {
			this.page = page
			this.userPageQueryList()
			console.log('page>', page)
		},
		update(item) {
            const { id } = item;
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
            this.showDrawer = true
            userGet({id}).then(res => {
                if (res.code === '0') {
                    const { roleList } = res.data;
                    roleList.map((item,i) => roleList[i] = item.id)
                    this.editedItem.roleIds = roleList;
                    this.editedItem = {...this.editedItem}
                }
            })
		},
		create() {
			this.editedIndex = -1
			this.editedItem = Object.assign({}, this.defaultItem)
			this.showDrawer = true
		},
		remove(item, idx) {
			//done this.close();
		},
		async save() {
			console.log('this.$Modal-->', this.$Modal)
			if (this.editedIndex > -1) {
				const { id, sex, roleIds, username } = this.editedItem
				this.updateLoading || (this.updateLoading = true)
				const res = await userUpdate({ id, sex, roleIds, username })
				this.updateLoading = false
				this.modal(res)
			} else {
				//create
				const { sex, roleIds, username, mobile, password } = this.editedItem
				this.createLoading || (this.createLoading = true)
				const res = await userAdd({ sex, roleIds, username, mobile, password })
				this.createLoading = false
				this.modal(res)
			}
			this.userPageQueryList()
			this.close()
		},
		modal(res,title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
				})
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg
				})
			}
		},
		close() {
			this.showDrawer = false
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},

		userPageQueryList() {
			const { page, pageSize, loading } = this
			if (loading) return
			this.loading = true
			userPageQueryList({
				page,
				pageSize
			})
				.then(res => {
					this.loading = false
					console.log('res roles->', res)
					if (res.code === '0') {
						const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data
						;(this.items = items), (this.page = currentPage), (this.totalNum = totalNum)
						console.log('this.items->', this.items)
					}
				})
				.catch(err => {
					this.loading = false
				})
		}
	},
	watch: {
		showDrawer(after) {
			after || this.close()
		}
	}
}
</script>
<style scoped>
.label-group {
	display: block;
}
.system-role {
	background-color: #fff;
}
</style>